package cn.lanqiao;

import cn.lanqiao.entity.User;
import cn.lanqiao.mapper.EmpMapper;
import cn.lanqiao.mapper.UserMapper;
import cn.lanqiao.vo.EmpVO;
import cn.lanqiao.vo.QueryEmpVO;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class MybatisTest {
    SqlSession session;

    @Before
    public void before() {
        //加载 mybatis 配置文件
        InputStream inputStream = MybatisTest.class.getClassLoader().getResourceAsStream("mybatis.xml");
        //构建sqlSession的工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //根据 sqlSessionFactory 产生 session
        session = sqlSessionFactory.openSession();
    }

    @After
    public void after() {
        session.close();
    }

    @Test
    public void testQueryUserList() {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> userList = userMapper.queryUserList();
        userList.forEach(user -> System.out.println(user));
    }

    @Test
    public void testInsert() {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = new User();
        user.setUserName("abcde");
        user.setPassword("123456");
        userMapper.insert(user);
        session.commit();
    }

    @Test
    public void testQuery() {
        EmpMapper empMapper = session.getMapper(EmpMapper.class);
        QueryEmpVO queryEmpVO = new QueryEmpVO();
        queryEmpVO.setEname("A");
//        queryEmpVO.setDname("ACCOUNTING");
        List<EmpVO> userList = empMapper.query(queryEmpVO);
        userList.forEach(user -> System.out.println(user));
    }
}
